package org.jsemantic.servicerules.examples.energy.services;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

import org.jsemantic.core.session.SemanticSession;
import org.jsemantic.servicerules.examples.energy.model.Customer;
import org.jsemantic.servicerules.examples.energy.model.Invoice;
import org.jsemantic.servicerules.examples.energy.model.MeterReading;
import org.jsemantic.servicerules.examples.energy.model.Tariff;
import org.jsemantic.servicerules.semanticservice.SemanticService;

public class InvoiceService extends SemanticService {

	public Invoice createInvoice(Customer customer, MeterReading reading) {

		SemanticSession session = getSemanticSession();

		session.execute(customer.getTariff());
		Tariff tariff = (Tariff) session.getContext().getResult("tariff");

		Invoice invoice = new Invoice();
		invoice.setNumber(generateInvoiceId());

		invoice.setDate(new Date());
		invoice.setCustomer(customer);

		BigDecimal total = calculate(tariff, reading);
		invoice.setTotal(total);

		PrinterService printerService = (PrinterService) (session.getContext()
				.getExternalContext()).getObject("printerService");

		printerService.printInvoice(invoice);

		session.dispose();
		session = null;

		return invoice;
	}

	private BigDecimal calculate(Tariff tariff, MeterReading reading) {

		BigDecimal totalPower = (tariff.getPpower().multiply(tariff.getPower()))
				.multiply(new BigDecimal(2));
		totalPower = totalPower.setScale(2, BigDecimal.ROUND_DOWN);

		BigDecimal totalConsume = tariff.getKwh().multiply(
				new BigDecimal(reading.getConsume()));

		totalConsume = totalConsume.setScale(2, BigDecimal.ROUND_DOWN);

		BigDecimal total = totalPower.add(totalConsume);
		total.setScale(2, BigDecimal.ROUND_DOWN);
		return total;
	}

	private Long generateInvoiceId() {
		Random seed = new Random();
		Long id = new Long(seed.nextLong());
		if (id < 0) {
			id *= -1;
		}
		return id;
	}
}
